package com.ybzl.collect.protocol;

import com.ybzl.collect.common.JSON;
import com.ybzl.collect.common.entity.SrcData;
import com.ybzl.collect.plugins.DistributePlugin;
import com.ybzl.collect.plugins.impl.HttpPlugin;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import com.ybzl.collect.common.entity.Result;

/**
 * 三方调用我司 --> 我司进行数据转发
 *  1.完成数据的存储
 *  2.记录每一次的调用记录（日志）
 */
@Slf4j
@RestController
@RequestMapping("/v1")
public class HttpForwardProtocol {

    @Value("${forward.url}")
    private String FORWARD_URL;

    /**
     * springboot中重置了content-type
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/forward/**", produces = "application/json;charset=UTF-8")
    public Result forward(HttpServletRequest request, HttpServletResponse response) {

        // http://192.168.1.167/prod-api/captchaImage
        if (!isJsonRequest(request)) {
            log.warn("Content-Type:{}",request.getContentType());
            return Result.error("非application/json类型请求");
        }
        try {
            //创建RequestConfig
            RequestConfig defaultRequestConfig = RequestConfig.custom()
                    //1、连接超时，指的是连接一个url的连接等待时间（毫秒）
                    .setConnectTimeout(5000)
                    //2、读取数据超时，指的是连接上一个url，获取response的返回等待时间（毫秒）
                    .setSocketTimeout(5000)
                    //3、从连接池获取连接的超时时间（毫秒）
                    .setConnectionRequestTimeout(5000)
                    //4、代理
                    //.setProxy(new HttpHost("newHost", 8080))
                    .build();

            //      这个超时可以设置为客户端级别,作为所有请求的默认值：
            CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

            String url = FORWARD_URL + request.getRequestURI().replace("/v1/forward", "");
            log.debug("target uil: " + url);

            HttpResponse resp = null;
            if (request.getMethod().equalsIgnoreCase("get")) {
                HttpGet httpget = new HttpGet(FORWARD_URL + request.getRequestURI().replace("/v1/forward", ""));
                //1.从默认的配置copy一份，进行客户端配置的自定义
                RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).build();
                httpget.setConfig(requestConfig);
                resp = httpclient.execute(httpget);

            } else if (request.getMethod().equalsIgnoreCase("post")) {
                HttpPost httpPost = new HttpPost(url);
                //1.公用默认的配置
                httpPost.setConfig(defaultRequestConfig);
                resp = httpclient.execute(httpPost);
            } else {
                log.warn("暂时不支持的协议类型." + request.getProtocol());
            }

            assert resp != null;
            if (resp.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = resp.getEntity();
                String message = EntityUtils.toString(resEntity, StandardCharsets.UTF_8);

                // 2.需要根据实际平台判断业务成功以后并进行事件的分发
                DistributePlugin distributePlugin = new HttpPlugin();
                distributePlugin.ayncDistribu(new SrcData(message));

                //3.避免数据透传过程中的二次序列化
                Object obj = JSON.parseJSONObject(message);
                return Result.success(obj);
            } else {
                log.error("出错啦，快去找一下原因！状态码是：" + resp.getStatusLine().getStatusCode());
            }
            return Result.error();

        } catch (Exception e) {
            log.info("异常: {}", e.getMessage(), e);
        }
        return Result.error();
    }

    /***
     *  判断是否是JSON类型的请求
     * @param request  request
     * @return
     */
    private boolean isJsonRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        return contentType != null && contentType.contains("application/json");
    }
}
